package org.invigorare.auctions;

import org.invigorare.auctions.data.SaleDataOpenHelper;
import static org.invigorare.auctions.data.SaleDataOpenHelper.*;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class AuctionSaleForm extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
    	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.auction_sale_form);

        // TODO: Use Intents to differentiate between NEW or EDIT EXISTING ENTRY requests
        // TODO: Consider moving all the Text Fields to sub-activities for a cleaner look (and to allow this to double as Viewer AND Editor) 
        
        associateFieldVars();
        setupAutocompletions();
        setupItemTable();
        
        // TODO: make Fees table
        
        /* Submit button */
        submitButton.setOnClickListener(new ClickListener_SubmitToDb());
        
    }
    
    EditText tollReceiptNo;
    TextView marketName, employeeInfo, saleDate, departDate, sellerInfo, agentInfo;
    AutoCompleteTextView sellerLicNo, agentLicNo;
    TableLayout itemTable;
    Button submitButton;
    
    /**
     * Finds the Views of each form field in this form and saves them as variables for easier access.
     */
    private void associateFieldVars() {
    	
    	/* Metadata */
    	marketName = (TextView) findViewById(R.id.saleform_label_market_name);
    	employeeInfo = (TextView) findViewById(R.id.saleform_label_employee_info);
    	tollReceiptNo = (EditText) findViewById(R.id.saleform_text_tollReceiptNo);
    	saleDate = (TextView) findViewById(R.id.saleform_label_sale_date);
    	departDate = (TextView) findViewById(R.id.saleform_label_depart_date);
    	
    	/* Seller & Buyer Info */
    	sellerLicNo = (AutoCompleteTextView) findViewById(R.id.saleform_text_seller_license);
    	agentLicNo = (AutoCompleteTextView)  findViewById(R.id.saleform_text_agent_license);
    	sellerInfo = (TextView) findViewById(R.id.saleform_label_seller_info);
    	agentInfo = (TextView) findViewById(R.id.saleform_label_agent_info);
    	
    	/* Auction Contents */
    	itemTable = (TableLayout) findViewById(R.id.saleform_table_items);

    	/* Fees */
    	// TODO:
    	
        /* Submit button */
    	submitButton = (Button) findViewById(R.id.button_saleform_submit);
    }
    
    private void setupAutocompletions() {
    	
        // TODO: Make a data adapter (ArrayAdapter) to populate AutoCompleteTextView text.
        
        // TODO: THINGS TO MAKE AUTOCOMPLETERS FOR:
        // TODO: Market Name
        // TODO: Toll Receipt Number
        
        // TODO: Auto-populate Today's date
        // TODO: Integrate a Date Picker widget with Date field
        
        // TODO: Commission Agent Name
        // TODO: Commission Agent License Number (autopopulate)
        
        // TODO: Farmer/Seller Name
        // TODO: Farmer/Seller Address (autopopulate)
        // TODO: Split Address field into subfields (might make more sense to make an AddressEditor sub-Activity)
        
        // TODO: Make an Auction Contents viewer
        // TODO: Make an Auction Contents EDITOR sub-Activity
    }
    
    /**
     * Sets up the ListView that lists the items sold in this auction,
     * with a default "Add" item entry.
     */
    private void setupItemTable() {
    	
    	Context context = getApplicationContext();
    	
    	// Move this "add" button to the XML, since there's always only 1 button
    	TableRow row = new TableRow(context);
    	row.addView(new TextView(context));
    	row.addView(new TextView(context));
    	row.addView(new TextView(context));
    	row.addView(new TextView(context));
    	
    	Button addButton = new Button(context);
    	addButton.setText(this.getString(R.string.saleform_addItem));
    	row.addView(addButton);
    	
    	// TODO: Connect a Button Event handler that pushes an Item Editor sub activity, GETS its result, and appends item to list.
    	
    	// Don't add a remove button by the "Add" button
    	{}
    	
    	itemTable.addView(row, new TableLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
    }
    
    private ContentValues getFormValues() {
    	
    	ContentValues values = new ContentValues();
    	
		values.put(MARKET_NAME, 	"[marketName from app settings]");
		values.put(EMPLOYEE_NO, 	"[employeeNo from app settings]");
		values.put(TOLLRECEIPT_NO, 	tollReceiptNo.getText().toString());
		values.put(SALE_TIMESTAMP, 	saleDate.getText().toString());
		
		values.put(SELLER_LICENSE, 	sellerLicNo.getText().toString());
		values.put(AGENT_LICENSE, 	agentLicNo.getText().toString());
		
		// TODO: add rest of values
		return values;
    }
    
    private class ClickListener_SubmitToDb implements View.OnClickListener {
    	
    	public void onClick(View v) {
    		/* Write form data to DB table */
    		SQLiteDatabase db = SaleDataOpenHelper.getWritableDb(AuctionSaleForm.this.getApplicationContext());
    		
    		long rowId = db.insert(
    	            SaleDataOpenHelper.SALE_TABLE_NAME,        	// The table to insert into.
    	            SaleDataOpenHelper.SALE_TABLE_NULL_COL,  	// A hack, SQLite sets this column value to null if values is empty.
    	            getFormValues()                           	// A map of column names, and the values to insert into the columns.
	        );
    		
    		/* TODO: pop up notification, confirmation? */
    		
    		/* Pop the current Activity */
    		AuctionSaleForm.this.finish();
    	}
    }
    
}